package com.yinhai.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.androidquery.AQuery;
import com.littlec.sdk.entity.CMMember;
import com.littlec.sdk.manager.CMIMHelper;
import com.lz.util.Utils;
import com.yinhai.constant.UrlConstant;
import com.yinhai.model.ContactsUser;
import com.yinhai.service.ContactUserServiceImpl;
import com.yinhai.util.NullUtils;
import com.yinhai.util.Util;
import com.yinhai.view.CustomGridView;

/**
 * 查看群组
 * 
 * @author lixh
 *
 */
public class ChatDetailGroupActivity extends Activity {
    private CustomGridView gridView;
    
    private List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
    
    private SimpleAdapter adapter;
    
    private String groupID, groupName;
    
    private EditText editText;
    
    private TextView tvtest;
    
    private Context context;
    
    private ChatDetailGroupActivity thisRef;
    
    private AQuery aq = null;
    
    private AlertDialog popDialog = null;
    
    private ContactUserServiceImpl contactUserServiceImpl;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail_group);
        thisRef = this;
        aq = new AQuery(this);
        contactUserServiceImpl = new ContactUserServiceImpl(this);
        Intent intent = this.getIntent();
        groupID = intent.getStringExtra("groupID");
        groupName = intent.getStringExtra("groupName");
        gridView = (CustomGridView)findViewById(R.id.gridview);
        editText = (EditText)findViewById(R.id.group_name);
        tvtest = (TextView)findViewById(R.id.tvtest);
        context = ChatDetailGroupActivity.this;
        initData();
        adapter =
            new SimpleAdapter(this, datas, R.layout.gridview_group_item, new String[] {"name"}, new int[] {R.id.title}) {
                public View getView(int position, View convertView, ViewGroup parent) {
                    View view = super.getView(position, convertView, parent);
                    if (Boolean.valueOf(datas.get(position).get("deleteFlag").toString())) {
                        view.findViewById(R.id.btn_delete).setVisibility(View.VISIBLE);
                    } else {
                        view.findViewById(R.id.btn_delete).setVisibility(View.GONE);
                    }
                    aq.id(view.findViewById(R.id.img)).image(UrlConstant.LOCAL_URI + "getPhoto?phone="
                        + datas.get(position).get("userPhone"),
                        Utils.getImageOptions(ChatDetailGroupActivity.this, R.drawable.tel_photo, Utils.IsImgSize));
                    return view;
                }
            };
        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int posion, long arg3) {
                String userPhone =
                    datas.get(posion).get("userPhone") == null ? "" : datas.get(posion).get("userPhone").toString();
                if (NullUtils.isNotEmpty(userPhone)) {
                    ContactsUser contactsUser = contactUserServiceImpl.findOnlineContactsUserByIMUserName(userPhone);
                    if (contactsUser != null) {
                        Intent it = new Intent(context, OnlineContactDetailActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("userId", contactsUser.getTelPhone());
                        it.putExtras(bundle);
                        context.startActivity(it);
                        return;
                    }
                    
                }
                Util.showMsg(context, "人员信息不完整，请重新同步通讯录数据");
            }
            
        });
    }
    
    public void initData() {
        editText.setText(groupName);
        // tvtest.setText("群组详细");
        tvtest.setText(groupName);
        List<CMMember> cmMembers = CMIMHelper.getCmGroupManager().getGroupMembersfromServer(groupID);
        
        for (CMMember member : cmMembers) {
            Map<String, Object> map1 = new HashMap<String, Object>();
            map1.put("id", member.getMemberId());
            map1.put("name", member.getMemberNick());
            map1.put("userPhone", member.getMemberId());
            map1.put("deleteFlag", false);
            datas.add(map1);
        }
        
    }
    
    OnClickListener cre = new OnClickListener() {
        
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            popDialog = Utils.showSetImageDialog(thisRef, "", "", btnPickClick, btnTakePhotoClick, null);
        }
    };
    
    /**
     * 拍照
     */
    OnClickListener btnTakePhotoClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (popDialog != null) {
                popDialog.dismiss();
            }
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            try {
                openFileOutput("headpic.jpg", MODE_WORLD_READABLE + MODE_WORLD_WRITEABLE);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            File headPic = new File(getFilesDir(), "headpic.jpg");
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(headPic));
            
            startActivityForResult(intent, 1);
        }
    };
    
    /**
     * 选择照片
     * */
    OnClickListener btnPickClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (popDialog != null) {
                popDialog.dismiss();
            }
            Intent intent = new Intent(Intent.ACTION_PICK, null);
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            startActivityForResult(intent, 2);
        }
    };
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            // Bundle bundle = data.getExtras();
            // Bitmap bitmap = (Bitmap) bundle.get("data");//
            // 获取相机返回的数据，并转换为Bitmap图片格式
            /*
             * try { // saveFile(bitmap,"111.jpg"); ContentResolver cr = this.getContentResolver(); String url =
             * MediaStore.Images.Media.insertImage(cr, bitmap, "集团", ""); } catch (Exception e) { e.printStackTrace(); }
             */
            
            File temp = new File(getFilesDir() + "/headpic.jpg");
            
            startPhotoZoom(Uri.fromFile(temp));
            
        } else if (requestCode == 2) { //
            if (data != null) {
                popDialog.dismiss();
                startPhotoZoom(data.getData());
            }
            
        } else if (requestCode == 3) {
            
            saveHeadPic(data);
            
        }
    }
    
    /**
     * 裁剪图片方法实现
     * 
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        try {
            openFileOutput("corptemp.jpg", MODE_WORLD_READABLE + MODE_WORLD_WRITEABLE);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        File tempPic = new File(getFilesDir(), "corptemp.jpg");
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 600);
        intent.putExtra("outputY", 600);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempPic));
        // intent.putExtra("return-data", false);
        startActivityForResult(intent, 3);
    }
    
    /**
     * 保存裁剪之后的图片数据 &nbsp;
     * 
     * @param picdata
     */
    
    private void saveHeadPic(Intent picdata) {
        Bitmap photo = BitmapFactory.decodeFile(getFilesDir() + "/corptemp.jpg");
        aq.id(R.id.group_img).image(Utils.toRoundCorner(photo, 300));
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] dataPhoto = baos.toByteArray();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        
    }
    
    // 返回
    public void doBack(View view) {
        onBackPressed();
    }
    
}
